<template>
  <view class="zmt-select-city">
    <uni-popup
      ref="cityPopup"
      type="bottom"
      :mask-click="false"
      @change="popupChange"
    >
      <view class="popup-content">
        <!-- 标题栏 -->
        <view class="popup-header">
          <view class="title">{{ title }}</view>
          <view class="close-icon" @click="close">
            <uni-icons type="close" size="20" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 搜索框 -->
        <view class="search-box">
          <uni-icons type="search" size="16" color="#999" class="search-icon"></uni-icons>
          <input
            type="text"
            v-model="searchKeyword"
            placeholder="搜索城市"
            class="search-input"
            @input="onSearch"
          />
          <view v-if="searchKeyword" class="clear-icon" @click="clearSearch">
            <uni-icons type="close" size="14" color="#999"></uni-icons>
          </view>
        </view>

        <!-- 内容区域 -->
        <view class="content-wrapper">
          <!-- 左侧省份列表 -->
          <view class="province-list" :class="{ 'hidden': isSearching }">
            <view
              v-for="province in provinces"
              :key="province.id"
              class="province-item"
              :class="{ 'active': selectedProvinceId === province.id }"
              @click="selectProvince(province.id)"
            >
              {{ province.name }}
            </view>
          </view>

          <!-- 右侧城市列表 -->
          <view class="city-list">
            <!-- 正常模式：按省份显示城市 -->
            <view v-if="!isSearching" class="normal-mode">
              <view
                v-for="city in currentCities"
                :key="city.id"
                class="city-item"
                :class="{ 'selected': isCitySelected(city.id) }"
                @click="toggleCity(city)"
              >
                <span>{{ city.name }}</span>
                <uni-icons v-if="isCitySelected(city.id)" type="checkbox-filled" size="15" color="#007aff" class="check-icon"></uni-icons>
              </view>
            </view>

            <!-- 搜索模式：显示搜索结果 -->
            <view v-else class="search-mode">
              <view v-if="searchResults.length > 0">
                <view v-for="result in searchResults" :key="result.provinceId" class="search-result-group">
                  <view class="province-title">{{ result.provinceName }}</view>
                  <view class="city-grid">
                    <view
                      v-for="city in result.cities"
                      :key="city.id"
                      class="city-item"
                      :class="{ 'selected': isCitySelected(city.id) }"
                      @click="toggleCity(city)"
                    >
                      <span>{{ city.name }}</span>
                      <uni-icons v-if="isCitySelected(city.id)" type="checkbox-filled" size="15" color="#007aff" class="check-icon"></uni-icons>
                    </view>
                  </view>
                </view>
              </view>
              <view v-else class="no-result">
                <uni-icons type="empty" size="48" color="#ccc"></uni-icons>
                <text>未找到相关城市</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 确认按钮 -->
        <view class="confirm-btn" @click="confirm">
          确认({{ selectedCities.length }})
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { provinceCityData, getProvinces, getCitiesByProvinceId, searchCities } from '../city-data.js';

export default {
  name: 'zmt-select-city',
  props: {
	openCity:{
		type:Boolean,
		default:false
	},
    title: {
      type: String,
      default: '选择城市'
    },
    // 是否多选，默认多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 默认选中的城市列表
    selectedCities: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 省份列表
      provinces: [],
      // 当前选中的省份ID
      selectedProvinceId: '',
      // 当前显示的城市列表
      currentCities: [],
      // 搜索关键词
      searchKeyword: '',
      // 是否处于搜索模式
      isSearching: false,
      // 搜索结果
      searchResults: [],
      // 选中的城市列表
      selectedCityList: []
    };
  },
  watch: {
    // 监听选中的省份变化，更新城市列表
    selectedProvinceId(newVal) {
      if (newVal) {
        this.currentCities = getCitiesByProvinceId(newVal);
      }
    },
    // 监听默认选中的城市变化
    selectedCities: {
      handler(newVal) {
        this.selectedCityList = [...newVal];
      },
      immediate: true,
      deep: true
    },
	openCity(val){
		if(val == true){
			this.open();
		}else{
			this.close()
		}
	}
  },
  mounted() {
    // 初始化省份列表
    this.provinces = getProvinces();
    
    // 默认选中第一个省份
    if (this.provinces.length > 0) {
      this.selectedProvinceId = this.provinces[0].id;
    }
  },
  methods: {
    // 打开弹窗
    open() {
      this.$refs.cityPopup.open();
    },
    // 关闭弹窗
    close() {
      this.$refs.cityPopup.close();
    },
    // 弹窗状态变化
    popupChange(e) {
      if (e.show === false) {
        this.$emit('close');
      }
    },
    // 选择省份
    selectProvince(provinceId) {
      this.selectedProvinceId = provinceId;
    },
    // 切换城市选中状态
    toggleCity(city) {
      const index = this.selectedCityList.findIndex(item => item.id === city.id);
      
      if (this.multiple) {
        // 多选模式
        if (index > -1) {
          // 取消选中
          this.selectedCityList.splice(index, 1);
        } else {
          // 选中
          this.selectedCityList.push(city);
        }
      } else {
        // 单选模式
        this.selectedCityList = [city];
      }
    },
    // 判断城市是否被选中
    isCitySelected(cityId) {
      return this.selectedCityList.some(item => item.id === cityId);
    },
    // 搜索城市
    onSearch() {
      if (this.searchKeyword.trim() === '') {
        this.isSearching = false;
        this.searchResults = [];
        return;
      }
      
      this.isSearching = true;
      this.searchResults = searchCities(this.searchKeyword);
    },
    // 清空搜索
    clearSearch() {
      this.searchKeyword = '';
      this.isSearching = false;
      this.searchResults = [];
    },
    // 确认选择
    confirm() {
      this.$emit('confirm', this.selectedCityList);
      this.close();
    }
  }
};
</script>

<style lang="scss" scoped>
.zmt-select-city {
  .popup-content {
    display: flex;
    flex-direction: column;
    height: 80vh;
    background-color: #fff;
    border-radius: 16px 16px 0 0;
  }

  // 标题栏样式
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #eee;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .close-icon {
      padding: 4px;
    }
  }

  // 搜索框样式
  .search-box {
    position: relative;
    padding: 12px 16px;
    border-bottom: 1px solid #eee;

    .search-icon {
      position: absolute;
      left: 28px;
      top: 50%;
      transform: translateY(-50%);
      z-index: 1;
    }

    .search-input {
      width: 100%;
      height: 36px;
      padding: 0 36px 0 32px;
      background-color: #f5f5f5;
      border-radius: 18px;
      font-size: 14px;
      color: #333;
    }

    .clear-icon {
      position: absolute;
      right: 28px;
      top: 50%;
      transform: translateY(-50%);
      z-index: 1;
      padding: 4px;
    }
  }

  // 内容区域样式
  .content-wrapper {
    display: flex;
    flex: 1;
    overflow: hidden;
  }

  // 省份列表样式
  .province-list {
    width: 100px;
    background-color: #f5f5f5;
    overflow-y: auto;

    &.hidden {
      display: none;
    }

    .province-item {
      padding: 16px 12px;
      font-size: 14px;
      color: #666;
      text-align: center;
      border-left: 3px solid transparent;

      &.active {
        background-color: #fff;
        color: #007aff;
        border-left-color: #007aff;
      }
    }
  }

  // 城市列表样式
  .city-list {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
  }

  // 正常模式下的城市列表
  .normal-mode {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
  }

  // 搜索模式下的结果列表
  .search-mode {
    .search-result-group {
      margin-bottom: 20px;

      .province-title {
        font-size: 14px;
        color: #999;
        margin-bottom: 12px;
      }

      .city-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
      }
    }

    .no-result {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 200px;
      color: #999;

      text {
        margin-top: 12px;
        font-size: 14px;
      }
    }
  }

  // 城市项样式
  .city-item {
    position: relative;
    padding: 8px 16px;
    background-color: #f5f5f5;
    border-radius: 16px;
    font-size: 14px;
    color: #333;
    border: 1px solid transparent;

    &.selected {
      background-color: #e6f2ff;
      border-color: #007aff;
      color: #007aff;
    }

    .check-icon {
      position: absolute;
      right: -4px;
      bottom: -4px;
    }
  }

  // 确认按钮样式
  .confirm-btn {
    margin: 16px;
    padding: 14px;
    background-color: #007aff;
    color: #fff;
    text-align: center;
    border-radius: 1.5rem;
    font-size: 16px;
    font-weight: 600;
  }
}
</style>